﻿using JmShared;
using JmShared.Models;
using Newtonsoft.Json;
using SuperWebSocket.SubProtocol;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WebSocketServer.Filters;

namespace WebSocketServer.Commands
{
    [LoggedInValidationFilter(Order = 0)]
    [LogTimeCommandFilter(Order = 1)]
    public class FileTransfer : JsonSubCommand<JiveClientSession, FileSlice>
    {
        private Dictionary<string, List<FileSlice>> _receivedSlices;
        protected override void ExecuteJsonCommand(JiveClientSession session, FileSlice slice)
        {
            if (_receivedSlices == null)
                _receivedSlices = new Dictionary<string, List<FileSlice>>();
            if (!_receivedSlices.ContainsKey(slice.TransferID))
                _receivedSlices[slice.TransferID] = new List<FileSlice>();

            _receivedSlices[slice.TransferID].Add(slice);

            if (_receivedSlices[slice.TransferID].Count == slice.SliceCount)
            {
                string data = "";
                foreach (FileSlice s in _receivedSlices[slice.TransferID].OrderBy(x => x.SliceNumber))
                {
                    data += s.Data;
                }
                switch (slice.TransferType)
                {
                    case JmShared.FileTransferType.CustomEmoticon:
                        ContactEmoticonTransfer ce = JsonConvert.DeserializeObject<ContactEmoticonTransfer>(data);
                        session.ReceiveEmoticon(ce);
                        break;
                    case FileTransferType.Avatar:
                        AvatarTransfer at = JsonConvert.DeserializeObject<AvatarTransfer>(data);
                        session.ReceiveAvatar(at);
                        break;
                }
                _receivedSlices.Remove(slice.TransferID);
            }
        }
    }
}
